﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;

namespace Toybox.SCM.Models.Accounts
{
	using Logger;
	using NicoSharp.Utilities;

	public class AccountGroupCollection : ObservableCollection<AccountGroup>
	{
		#region [Static]

		public static AccountGroupCollection Load(string filePath, AccountCollection accounts)
		{
			var groups = new AccountGroupCollection();

			try
			{
				using (var fs = new FileStream(filePath, FileMode.Open))
				using (var sr = new StreamReader(fs, Encoding.Unicode))
				{
					var elements = CsvUtility.Parse(sr.ReadToEnd());
					for (int n = 0; n < elements.Length; n++)
					{
						if (elements[n][0] != AccountGroup.CSV_START_TAG)
							continue;

						var list = new List<string[]>();

						list.Add(elements[++n]); // 固定
						list.Add(elements[++n]); // ボタン機能 
						list.Add(elements[++n]); // IsUse
						list.Add(elements[++n]); // Priority
						list.Add(elements[++n]); // UId

						groups.Add(new AccountGroup(accounts, list.ToArray()));
					}
				}
			}
			catch (Exception ex)
			{
				TraceLogger.WriteLine(ex.ToString());
			}

			return groups;
		}

		public static void Save(string filePath, AccountGroupCollection groups)
		{
			try
			{
				using (var fs = new FileStream(filePath, FileMode.Create))
				using (var sw = new StreamWriter(fs, Encoding.Unicode))
				{
					foreach (var group in groups)
					{
						sw.Write(group.ToString());
					}
				}
			}
			catch (Exception ex)
			{
				TraceLogger.WriteLine(ex.ToString());
			}
		}

		#endregion [Static]


		#region Public Methods

		#endregion Public Methods

	}
}
